<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;


class TypeeController extends CommonController
{
     public function create()
	 {
		 //查询数据库
		 $list = \DB::select("select * from type order by concat(path,id) asc");
		 //判断数据是否拿到
		 if(!empty($list)){
			 //处理信息
			 foreach($list as $v){
				    //获取path中的逗号出现的次数，用户区分几层类
				    $m = substr_count($v->path,',');
				    //生成缩进
			        $v->name = str_repeat(" &nbsp; ",($m-1)*2)."|--".$v->name;
			 }
		 }
		 return view('admin.type.create2',['list'=>$list]);
	 }
	 
	 
	 public function store(Request $request)
	 {
		  //获取添加的子类值
		  $name = $request->childname;
		  $id = $request->pid;
		  if(!empty($name)){
		       //数据库查询分类是否存在
		       $list=\DB::table('type')->where('name',"{$name}")->first();
		       //判断添加的分类是否存在
               if(!empty($list)){
		  	   	echo '<script>alert("子类已经存在");</script>';
		  	       return view('admin.typee.create2');
               }else{
		  	      //执行数据查询,获取父类pid;
		  	      $list=\DB::table('type')->where('id',"{$id}")->first();
		  	      //得到子类路径
		  	      $path=$list->path.$id.',';
		  	      //放入数据库
		  	      $result = \DB::table('type')->insertGetId(['name'=>"{$name}",'pid'=>"{$id}",'path'=>"{$path}"]);
		  	      			//判断
		  	   if($result>0){
		  	   	echo '<script>alert("添加成功");</script>';
		  	   	 //数据库查询
                      $list = \DB::select("select * from type order by concat(path,id) asc");
		             //处理信息
		             foreach($list as $v){
		  	   	 //获取path中的逗号
		  	        $m = substr_count($v->path,',');
		  	        //生成缩进
		  	        $v->name = str_repeat(" &nbsp; ",($m-1)*8)."|--".$v->name;
		               }
		             return view("admin.type.index",['list'=>$list]);
		  	   	
		  	   }else{
		  	   	echo '<script>alert("添加失败");</script>';
		  	   	return view('admin.typee.create2');
		  	  }
		    }
		  }else{
			   echo '<script>alert("添加子类不能为空");</script>';
			   //查询数据库
		       $list = \DB::select("select * from type order by concat(path,id) asc");
		       //判断数据是否拿到
		       if(!empty($list)){
			   //处理信息
			   foreach($list as $v){
				    //获取path中的逗号出现的次数，用户区分几层类
				    $m = substr_count($v->path,',');
				    //生成缩进
			        $v->name = str_repeat(" &nbsp; ",($m-1)*2)."|--".$v->name;
			    }
		      }
		      return view('admin.type.create2',['list'=>$list]);
		  }			 
	 }
}
